package com.bxx.ermall.controller;


import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.bxx.ermall.common.dto.OrderDto;
import com.bxx.ermall.common.lang.Result;
import com.bxx.ermall.entity.Order;
import com.bxx.ermall.service.OrderService;
import com.bxx.ermall.util.ShiroUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import org.springframework.stereotype.Controller;

import java.time.LocalDateTime;
import java.util.List;

/**
 * <p>
 *  前端控制器
 * </p>
 *
 * @author buxiaoxing
 * @since 2021-02-02
 */
@RestController("/order")
public class OrderController {

    @Autowired
    OrderService orderService;
    //创建订单
    @PostMapping("/add")
    public Result add(@RequestBody String data){
        JSONObject jsonObject = JSON.parseObject(data);
        Integer goodsId = (Integer)jsonObject.get("goodsId");
        Integer address = (Integer)jsonObject.get("address");
        Order temp = new Order();
        temp.setAddress(address);
        temp.setGoodsId(goodsId);
        temp.setState(0);
        temp.setCreateTime(LocalDateTime.now());
        temp.setMemberId(ShiroUtil.getProfile().getId());
        orderService.save(temp);
        return Result.succ(null);
    }

    //删除订单
    @PostMapping("/delete")
    public Result delete(@RequestBody String data){
        JSONObject jsonObject = JSON.parseObject(data);
        Integer id = (Integer)jsonObject.get("id");
        Order order = orderService.getById(id);
        if(order.getState() != 0){
            return Result.fail("订单已发货，无法取消");
        }
        orderService.removeById(id);
        return Result.succ(null);
    }

    //发货

    @PostMapping("/ship")
    public Result ship(@RequestBody String data){
        JSONObject jsonObject = JSON.parseObject(data);
        Integer id = (Integer)jsonObject.get("id");
        Order order = orderService.getById(id);
        if(order.getState() == 0){
            order.setState(1);
            orderService.updateById(order);
            return Result.succ(null);
        }
        return Result.fail("订单状态错误");


    }

    //收货

    @PostMapping("/receipt")
    public Result receipt(@RequestBody String data){
        JSONObject jsonObject = JSON.parseObject(data);
        Integer id = (Integer)jsonObject.get("id");
        Order order = orderService.getById(id);
        if(order.getState() == 1){
            order.setState(2);
            orderService.updateById(order);
            return Result.succ(null);
        }
        return Result.fail("订单状态错误");
    }

    //列表
    @GetMapping("/list")
    public Result list(){
        List<OrderDto> data = orderService.orderList();
        return Result.succ(data);
    }
}

